import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

// create an axios instance
const request = axios.create({
  baseURL: '/api', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
request.interceptors.request.use(
  (config) => {
    // 注入token
  //  this.$store.getters
    // store.getters.token => 请求头里面
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  }, (error) => {
    // 失败执行promise
    return Promise.reject(error)
  })
// 响应拦截器
request.interceptors.response.use((response) => {
  const { data, message, success } = response.data // 默认json格式
  console.dir(response)
  if (success) {
    return data
  }
  Message({ type: 'error', message })
  return Promise.reject(new Error(message))
}, async(error) => {
  // error.message
  if (error.response.status === 401) {
    store.dispatch('user/logoutActions')
    Message.error('登录过期')
    return Promise.reject(new Error(error.response.message))
  }
  Message({ type: 'error', message: error.message })
  return Promise.reject(error)
})

export default request
